//
//  ZSY_CityHunterListViewController.m
//  ZSY_BreadTrip
//
//  Created by 张诗宇 on 15/12/28.
//  Copyright © 2015年 张诗宇. All rights reserved.
//

#import "ZSY_CityHunterListViewController.h"
#import "ZSY_CityHunterListTableViewCell.h"
#import "ZSY_CityModel.h"
#import "ZSY_CityHunterCItyViewController.h"
#import "ZSY_CityHunterDetailViewController.h"


@interface ZSY_CityHunterListViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) ZSY_BaseTableView *cityHunterTableView;
@property (nonatomic, retain) NSMutableArray *hunterArray;
@property (nonatomic, copy) NSString *cityString;

@property(nonatomic,assign)NSInteger nextPage;//记录下一页
@property(nonatomic,assign)BOOL isUpLoading;//标记上拉操作还是下拉操作，yes为上拉



@end

@implementation ZSY_CityHunterListViewController

- (void)dealloc {
    [_cityString release];
    [_cityHunterTableView release];
    [_hunterArray release];
    [super dealloc];
}

// 在视图将要出现的时候,改变navigation左button的文字
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.cityString = [[NSUserDefaults standardUserDefaults] objectForKey:@"city"];
    self.navigationItem.leftBarButtonItem.title = self.cityString;
}
// 在视图出现的时候,刷新页面数据
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.cityString = [[NSUserDefaults standardUserDefaults] objectForKey:@"city"];
//    self.navigationItem.leftBarButtonItem.title = self.cityString;
    [self addHeaderChange];
    [self.cityHunterTableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.view.backgroundColor = [UIColor colorWithRed:248 / 255.0 green:243 / 255.0 blue:233 / 255.0 alpha:1];
    
    // 左上角城市button
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"上海" style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonAction:)];
    
    
    self.hunterArray = [NSMutableArray array];
//    self.automaticallyAdjustsScrollViewInsets = YES;
    CGRect frame = self.view.frame;
    frame.size.height -= 104;
    self.cityHunterTableView = [[ZSY_BaseTableView alloc] initWithFrame:frame style:UITableViewStylePlain];
    self.cityHunterTableView.backgroundColor = [UIColor colorWithRed:248 / 255.0 green:243 / 255.0 blue:233 / 255.0 alpha:1];
    self.cityHunterTableView.delegate = self;
    self.cityHunterTableView.dataSource = self;
    [self.view addSubview:_cityHunterTableView];
    // 取消cell 的分割线
    self.cityHunterTableView.separatorStyle = NO;
    [self.cityHunterTableView registerClass:[ZSY_CityHunterListTableViewCell class] forCellReuseIdentifier:@"cell"];
    
//    NSString *url = @"http://api.breadtrip.com/hunter/products/more/?city_name=%E5%A4%A7%E8%BF%9E&lat=38.87983189240757&lng=121.5418244594445&sign=897b8a82916306564b51377939cdc837&sorted_id=1&start=0";
    self.isUpLoading = NO;
    
    // 2.集成上拉下拉功能
    [self addHeader];
    
    [_cityHunterTableView release];
    
}


#pragma mark --下拉刷新
- (void)addHeader
{
    //    __unsafe_unretained typeof(self) vc = self;
    
    __block ZSY_CityHunterListViewController *vc = self;//因为block块里用self会报警告,所以需要将self声明成block变量
    
    // 添加下拉刷新头部控件
    [self.cityHunterTableView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        vc.nextPage = 0;//记录页码的
        vc.isUpLoading = NO;//标记为下拉操作
        [vc getDataList:vc.nextPage];//重新请求数据
        
    }];
    
    NSFileManager *manager1 = [NSFileManager defaultManager];
    
    NSString *filePath = [ZSY_AppTools createFilePathFromDocumentWithFolders:@[@"CityHunter", @"CityHunterViewController", @"All"] fileName:@"cityHunter.txt"];
    
    //    NSLog(@"~~~~~%@", filePath);
    if ([manager1 fileExistsAtPath:filePath]) {
        NSData *data = [NSData dataWithContentsOfFile:filePath];
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSArray *productArray = [dic objectForKey:@"product_list"];
        for (NSDictionary * dic in productArray) {
            ZSY_CityModel *city = [[ZSY_CityModel alloc] init];
            [city setValuesForKeysWithDictionary:dic];
            [self.hunterArray addObject:city];
            [city release];
        }
        [self.cityHunterTableView headerEndRefreshing];
        [self.cityHunterTableView reloadData];
        
    }
    
    
#pragma mark 自动刷新(一进入程序就下拉刷新)
    else{
        
        [self.cityHunterTableView headerBeginRefreshing];
    }
    
}

- (void)addHeaderChange {
    //    __unsafe_unretained typeof(self) vc = self;
    
    __block ZSY_CityHunterListViewController *vc = self;//因为block块里用self会报警告,所以需要将self声明成block变量
    
    // 添加下拉刷新头部控件
    [self.cityHunterTableView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        vc.nextPage = 0;//记录页码的
        vc.isUpLoading = NO;//标记为下拉操作
        [vc getDataList:vc.nextPage];//重新请求数据
        
    }];
    [self.cityHunterTableView headerBeginRefreshing];

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZSY_CityHunterListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    ZSY_CityModel *city = [_hunterArray objectAtIndex:indexPath.row];
    cell.city = city;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 330;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _hunterArray.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //点击后自动取消选中置灰效果
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    ZSY_CityHunterDetailViewController *cityDetailVC = [[ZSY_CityHunterDetailViewController alloc] init];
    
    cityDetailVC.cityModel = [_hunterArray objectAtIndex:indexPath.row];
    [self.navigationController pushViewController:cityDetailVC animated:YES];
    [cityDetailVC release];
}

// 左上角点击实现
- (void)leftButtonAction:(UIBarButtonItem *)button {
    ZSY_CityHunterCItyViewController *cityVC = [[ZSY_CityHunterCItyViewController alloc] init];
    [self presentViewController:cityVC animated:YES completion:^{
        
        
    }];
    [cityVC release];
}

#pragma 用AFN请求数据
- (void)getDataList:(NSInteger)next {
//    self.cityString = @"上海";
    NSString *url = [NSString stringWithFormat:@"http://api.breadtrip.com/hunter/products/more/?city_name=%@&lat=38.87983189240757&lng=121.5418244594445&sign=897b8a82916306564b51377939cdc837&sorted_id=1&start=0", self.cityString];
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    [self.hunterArray removeAllObjects];
    
    [ZSY_AppTools creatingDataTask:url parameters:nil Cookie:nil User_Agent:nil successAFNBlock:^(id resuposeObject) {
        NSDictionary *result = resuposeObject;
        NSArray *productArray = [result objectForKey:@"product_list"];
        for (NSDictionary * dic in productArray) {
            ZSY_CityModel *city = [[ZSY_CityModel alloc] init];
            [city setValuesForKeysWithDictionary:dic];
            [self.hunterArray addObject:city];
            [city release];
        }
        [self.cityHunterTableView headerEndRefreshing];

        [self.cityHunterTableView reloadData];
        
        
        NSData *data = [NSJSONSerialization dataWithJSONObject:resuposeObject options:NSJSONWritingPrettyPrinted error:nil];
        NSString *filePath = [ZSY_AppTools createFilePathFromDocumentWithFolders:@[@"CityHunter", @"CityHunterViewController", @"All"] fileName:@"cityHunter.txt"];
        [ZSY_AppTools saveDataOnLocal:data localPath:filePath];
    }];

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
